<template>
  <div class="page-Body">
    <h2 class="page-title">视频管理</h2>
    <!-- 表单 -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="视频名称">
        <el-input
          v-model="formInline.title"
          placeholder="请输入视频名称"
          clearable
          style="width: 350px"
          v-noSpace
        />
      </el-form-item>
      <el-form-item label="空间名称">
        <el-select
          v-model="formInline.spaceId"
          placeholder="请选择空间名称"
          clearable
          style="width: 400px"
        >
          <el-option
            v-for="item in getSpaceListAll"
            :key="item.spaceId"
            :label="item.name"
            :value="item.spaceId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="Search">搜索</el-button>
        <el-button @click="Reset">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 新增对话框组件 -->
    <el-button plain @click="AddOpenDialog" class="el-DiaButton" type="primary">
      添加
    </el-button>
    <AddVideo_Dialog
      @confirm="AddConfirm"
      @cancel="AddClose"
      :dialogAdd="dialogAdd"
    />
    <!-- 表格 -->
    <el-table
      :data="tableData"
      border
      stripe
      fit
      empty-text="暂无数据"
      show-header
      v-loading="loading"
      size="default"
      element-loading-text="Loading..."
      :header-cell-style="{ background: '#e7e1fb' }"
      style="width: 100%"
      max-height="540px"
    >
      <el-table-column prop="id" label="序号" />
      <el-table-column prop="title" label="视频名称" />
      <el-table-column prop="spaceName" label="空间名称" width="500">
        <template #default="scope">
          <span>
            {{
              scope.row.spaceVOList?.map((item) => item.name).join('、') || '-'
            }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="coverUrl" label="封面图片" width="200">
        <template #default="scope">
          <el-image
            v-if="scope.row.coverUrl"
            :src="scope.row.coverUrl"
            fit="cover"
            style="width: 60px; height: 60px"
          />
          <span v-else>暂无封面</span>
        </template>
      </el-table-column>

      <el-table-column prop="releaseStatus" label="状态" v-slot="scope">
        <span>
          {{ scope.row.releaseStatus === 0 ? '草稿' : '已发布' }}
        </span>
      </el-table-column>
      <el-table-column prop="uploadTime" label="添加时间" />
      <el-table-column
        align="center"
        fixed="right"
        label="操作"
        v-slot="scope"
        width="200"
      >
        <el-button link type="primary" @click="DetailsOpenDialog(scope.row.id)">
          详情
        </el-button>
        <el-button link type="primary" @click="ModifyOpenDialog(scope.row.id)">
          编辑
        </el-button>
        <el-button link type="danger" @click="Del(scope.row.id)">
          删除
        </el-button>
      </el-table-column>
    </el-table>
    <!-- 修改对话框组件 -->
    <ModifyVideo_Dialog
      :dialogModify="dialogModify"
      :ModifyId="ModifyId"
      @confirm="ModifyConfirm"
      @cancel="ModifyClose"
    />

    <!-- 详情对话框组件 -->
    <DetailsVideo_Dialog
      :dialogDetails="dialogDetails"
      :DetailsVideoId="DetailsVideoId"
      @cancel="DetailsClose"
    />
    <!-- 分页器 -->
    <div class="pagination-block">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[20, 40, 80, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup name="FacilityManagementPage">
import { getVideoList, delVideo } from '@/api/Venue/video';
import { getSpaceList } from '@/api/Venue/facility';
import { ref, onMounted, nextTick } from 'vue';
import DetailsVideo_Dialog from '@/components/Venus/video/DetailsVideo_Dialog.vue';
import AddVideo_Dialog from '@/components/Venus/video/AddVideo_Dialog.vue';
import ModifyVideo_Dialog from '@/components/Venus/video/ModifyVideo_Dialog.vue';
// 分页变量
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);

// 对话框
const dialogAdd = ref(false);
const dialogModify = ref(false);
const dialogDetails = ref(false);
const ModifyId = ref('');
const DetailsVideoId = ref('');
// 表单数据
const formInline = ref({
  title: '',
  spaceId: '',
});
// 列表数据+表单校验
const tableData = ref([]);
const loading = ref(true);
const getSpaceListAll = ref([]);
// 分页逻辑
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1;
  // 根据是否有搜索条件决定调用哪个方法
  if (hasSearchConditions()) {
    Search();
  } else {
    VideoList();
  }
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  // 根据是否有搜索条件决定调用哪个方法
  if (hasSearchConditions()) {
    Search();
  } else {
    VideoList();
  }
};
// 获取列表
const VideoList = async () => {
  loading.value = true;
  const res = await getVideoList({
    current: currentPage.value,
    size: pageSize.value,
    query: {},
  });
  if (res.data.code === 200) {
    tableData.value = res.data.data.items;
    total.value = res.data.data.counts || 0;
    loading.value = false;
  }
};
// 检查搜索条件是否为空
const hasSearchConditions = () => {
  const { title, spaceId } = formInline.value;
  return title || spaceId;
};
// 搜索
const Search = async () => {
  if (!hasSearchConditions()) {
    // eslint-disable-next-line no-undef
    ElMessage.warning('请至少输入一个搜索条件');
    return;
  }

  try {
    loading.value = true;
    const res = await getVideoList({
      current: currentPage.value,
      size: pageSize.value,
      query: { ...formInline.value },
    });

    if (res.data.code === 200) {
      tableData.value = res.data.data.items;
      total.value = res.data.data.counts || 0;
    }
  } catch (error) {
    console.error('搜索失败:', error);
  } finally {
    loading.value = false;
  }
};
// 重置
const Reset = () => {
  // 如果当前已经是空值状态，直接返回
  if (formInline.value.title === '' && formInline.value.spaceId === '') {
    return;
  }
  formInline.value = {
    title: '',
    spaceId: '',
  };
  currentPage.value = 1; // 重置页码
  VideoList();
};

// 删除
const Del = async (id) => {
  console.log(id);

  // eslint-disable-next-line no-undef
  ElMessageBox.confirm('确定删除?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await delVideo(id);
      if (res.data.code === 200) {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: '删除成功',
          type: 'success',
        });
        VideoList();
      } else {
        // eslint-disable-next-line no-undef
        ElMessage({
          message: res.data.msg,
          type: 'warning',
        });
      }
    })
    .catch(() => {});
};
// 获取空间下拉
const getSpaceOption = async () => {
  const res = await getSpaceList();
  if (res.data.code === 200) {
    getSpaceListAll.value = res.data.data || [];
  }
  console.log(res);
};
// 添加功能对话框
const AddOpenDialog = () => {
  dialogAdd.value = true;
};

const AddConfirm = () => {
  dialogAdd.value = false;
  VideoList();
};
const AddClose = () => {
  dialogAdd.value = false;
};

// 修改功能对话框
const ModifyOpenDialog = (id) => {
  console.log('修改', id);
  ModifyId.value = id; // 先设置数据
  nextTick(() => {
    dialogModify.value = true; // 再打开对话框
  });
};

const ModifyConfirm = () => {
  dialogModify.value = false;
  VideoList();
};
const ModifyClose = () => {
  dialogModify.value = false;
};

// 详情功能对话框
const DetailsOpenDialog = (id) => {
  console.log('详情', id);
  DetailsVideoId.value = id; // 先设置ID
  nextTick(() => {
    dialogDetails.value = true; // 再打开对话框
  });
};
const DetailsClose = () => {
  dialogDetails.value = false;
};

onMounted(() => {
  VideoList();
  getSpaceOption();
});
</script>

<style lang="scss" scoped>
.el-DiaButton {
  width: 120px;
  height: 40px;
  border-radius: 4px;
  margin-bottom: 20px;
  border: 1px solid #c7d4ff;
}
</style>
